import { allowEditMenu, query, table } from '../data/data';
import { deleteMenu, getMenuById, listMenu, type IMenu } from '@/api/modules/auth/menu';
import { form, resetForm } from './form';

export const create = () => {
  allowEditMenu.value = true;
  resetForm();
};

export const list = async () => {
  table.value.loading = true;
  /* fetchData */
  const { data } = await listMenu(query.value);
  table.value.data = buildTree(data.data);
  table.value.loading = false;
};
export const edit = async (id?: string) => {
  const targetId = id ? id : table.value.keys[0];
  const { data } = await getMenuById(`${targetId}`);
  form.value = data.data;
  allowEditMenu.value = true;
  table.value.loading = false;
};
export const remove = async (id?: string) => {
  const target = id ? id : table.value.keys;
  await deleteMenu(`${target}`);
  await list();
};
export const detail = () => {
  allowEditMenu.value = true;
  table.value.loading = false;
};

export const buildTree = (data: IMenu[], parentId = '0') => {
  const result = [];
  for (const item of data) {
    if (item.parentId === parentId) {
      item.children = buildTree(data, item.menuId);
      if (item.children?.length === 0) {
        item.children = [];
      }
      result.push(item);
    }
  }
  return result;
};
export const search = () => {
  query.value.pageNum = 1;
  list();
};
